﻿#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;

using Ionic.Zip;
using Ionic.Zlib;

using octalforty.Chinchillin.Shared.Deployment;
using octalforty.Chinchillin.Shared.Deployment.Metadata;
using octalforty.Chinchillin.Shared.Deployment.Resources;

namespace octalforty.Chinchillin.Actions.Fs
{
    /// <summary>
    /// Pepresents an action which, when executed, backs up specified directory.
    /// </summary>
    [Action(Name)]
    public class BackupDirectoryAction : ActionBase
    {
        #region Private Constants
        private const string Name = "backup-directory";
        private const string Location = "location";
        private const string BackupLocation = "backup-location";
        private const string BackupResource = "backup-resource";
        private const string CompressionLevel = "compression-level";

        private static readonly ActionInfo actionInfo = new ActionInfo
            {
                Name = Name,
                Arguments = new[]
                    {
                        new ActionArgumentInfo(Location, ActionArgumentType.Uri),
                        new ActionArgumentInfo(BackupLocation, ActionArgumentType.Uri),
                        new ActionArgumentInfo(BackupResource, ActionArgumentType.Uri),
                        new ActionArgumentInfo(CompressionLevel, ActionArgumentType.String)
                    }
            };
        #endregion

        public IResourceProvider ResourceProvider
        { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="BackupDirectoryAction"/> class.
        /// </summary>
        public BackupDirectoryAction() :
            base(actionInfo)
        {
        }

        public override void Execute(IActionExecutionContext executionContext)
        {
            var location = (Uri)executionContext.Arguments[Location];

            //
            // If "backup-location" is specified, we're backing up to a directory
            if(executionContext.Arguments.ContainsKey(BackupLocation))
            {
                var backupLocation = (Uri)executionContext.Arguments[BackupLocation];

                /*var syncManager = new SyncManager<string, string>(
                    new DelegateSyncCallback<string, string>());
                syncManager.SyncOneWay()
                 * */

                TracingManager.TraceEvent(executionContext, TraceEventType.Information, 0, string.Format("Backing up '{0}' to '{1}'", location, backupLocation));

                //
                // TODO: Replace with SyncManager so that no unneccessary file IO is performed?
                CopyDirectory(location.LocalPath, backupLocation.LocalPath, 
                    (s, t) => TracingManager.TraceEvent(executionContext, TraceEventType.Verbose, 0,
                        string.Format("Backing up '{0}' to '{1}'", s, t)));

                TracingManager.TraceEvent(executionContext, TraceEventType.Information, 
                    0, string.Format("Backed up '{0}' to '{1}'", location, backupLocation));
            } // if
            else if(executionContext.Arguments.ContainsKey(BackupResource))
            {
                var backupResource = (Uri)executionContext.Arguments[BackupResource];

                TracingManager.TraceEvent(executionContext, TraceEventType.Information, 
                    0, string.Format("Backing up '{0}' to '{1}'", location, backupResource));

                using(var zipFile = new ZipFile(Encoding.UTF8))
                {
                    zipFile.CompressionLevel = executionContext.Arguments.ContainsKey(CompressionLevel) ?
                        (CompressionLevel)Enum.Parse(typeof(CompressionLevel), executionContext.Arguments[CompressionLevel].ToString(), true) :
                        Ionic.Zlib.CompressionLevel.BestCompression;

                    zipFile.AddDirectory(location.LocalPath, "");

                    zipFile.Save(backupResource.LocalPath);
                } // using

                TracingManager.TraceEvent(executionContext, TraceEventType.Information, 0, string.Format("Backed up '{0}' to '{1}'", location, backupResource));
            } // else if
        }

        public static void CopyDirectory(string sourceDirectory, string targetDirectory, Action<string, string> fileCopyCallback)
        {
            if(!Directory.Exists(targetDirectory))
                Directory.CreateDirectory(targetDirectory);

            var files = Directory.GetFiles(sourceDirectory);

            foreach(var file in files)
            {
                var name = Path.GetFileName(file);
                var dest = Path.Combine(targetDirectory, name);

                File.Copy(file, dest, true);

                if(fileCopyCallback != null)
                    fileCopyCallback(file, dest);
            }

            var folders = Directory.GetDirectories(sourceDirectory);

            foreach(var folder in folders)
            {
                var name = Path.GetFileName(folder);
                var dest = Path.Combine(targetDirectory, name);

                CopyDirectory(folder, dest, fileCopyCallback);
            }
        }
    }
}